package utility


import (
	"encoding/json"
	"errors"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"fmt"
	"os"
)

type Config struct {
	Host   string
	Port    string
	Database string
	Username string
	Password string
}

var Db  *gorm.DB

func GetDb() *gorm.DB {

	return Db

}

func init()  {
	fmt.Println("mysql init")
	config,_ := GetConfig()
	Db       = InitDB(config)

}

func GetConfig() (Config,error) {
	var conf Config
	filePtr, err := os.Open("./config/mysql.json")
	if err != nil {
		fmt.Println("文件打开失败 [Err:%s]", err.Error())
		return conf,errors.New("配置文件未找到")
	}
	defer filePtr.Close()

	decoder := json.NewDecoder(filePtr)
	err = decoder.Decode(&conf)
	if err != nil {
		return conf,errors.New("配置文件解析失败")
		fmt.Println("解码失败", err.Error())
	} else {
		fmt.Println("解码成功")
		fmt.Println(conf)

	}
	return conf,err
}

//数据库连接
func InitDB(config Config) *gorm.DB {

	fmt.Println("mysql 连接")
	driverName := "mysql"
	host := config.Host
	port := config.Port
	database := config.Database
	username := config.Username
	password := config.Password
	charset := "utf8"
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		database,
		charset,
	)

	db, err := gorm.Open(driverName, args)

	db.SingularTable(true)
	//db, err := gorm.Open("mysql", "user:islot@/blog?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		panic("failed to connect database,err:" + err.Error())
	}

	////自动创建数据表
	//db.AutoMigrate(&User1{})

	return db

}
